package com.px.web.controller.system;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.px.common.core.controller.BaseController;
import com.px.common.core.domain.AjaxResult;
import com.px.common.core.domain.entity.SysDictData;
import com.px.common.core.page.TableDataInfo;
import com.px.common.utils.StringUtils;
import com.px.device.domain.RoutesInfo;
import com.px.device.service.IDroneInfoService;
import com.px.device.service.IRoutesInfoService;
import com.px.framework.aes.AesSecurityParameter;
import com.px.plan.domain.Plan;
import com.px.plan.domain.PlanAction;
import com.px.plan.service.IPlanActionService;
import com.px.system.domain.DroneInfo;
import com.px.system.domain.vo.IndexVo;
import com.px.system.service.ISysDeptService;
import com.px.system.service.ISysDictDataService;
import com.px.task.domain.TaskRecord;
import com.px.task.service.ITaskCalendarService;
import com.px.task.service.ITaskRecordService;
import com.px.task.vo.TaskVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;


@Api("首页接口")
@RestController
@RequestMapping("/index")
public class IndexController extends BaseController {

    @Autowired
    IPlanActionService planActionService;
    @Autowired
    IDroneInfoService droneInfoService;
    @Autowired
    ISysDictDataService dictDataService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ITaskRecordService taskRecordService;
    @Autowired
    private ITaskCalendarService taskCalendarService;
    @Autowired
    private IRoutesInfoService routesInfoService;

    @ApiOperation("首页测试接口")
    @PostMapping("/IndexOne")
    public AjaxResult IndexOne()
    {
        return AjaxResult.success();
    }

    @ApiOperation("预案状态分布")
    @GetMapping("planStateStatistics")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult planStateStatistics()
    {
        List<JSONObject> result = new ArrayList<>();

        return AjaxResult.success(result);
    }

    @ApiOperation("进行中的行动列表")
    @GetMapping("actionStatistics")
    @AesSecurityParameter(outEncode = true)
    public TableDataInfo actionStatistics(PlanAction planAction)
    {
        startPage();
        planAction.setStatus(1);
        List<PlanAction> list = planActionService.selectPlanActionList(planAction);
        return getDataTable(list);
    }

    @ApiOperation("无人机机型统计")
    @GetMapping("droneTypeStatistics")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult droneTypeStatistics()
    {
        JSONObject result = new JSONObject();
        List<DroneInfo> droneInfos = droneInfoService.selectDroneInfoList(new DroneInfo());
        SysDictData dictData = new SysDictData();
        dictData.setDictType("device_type");
        List<SysDictData> dictDatas = dictDataService.selectDictDataList(dictData);
        Map<String, String> dictMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(dictDatas)) {
            dictDatas.forEach(d-> dictMap.put(d.getDictValue(), d.getDictLabel()));
        }

        if (!dictMap.isEmpty() && CollectionUtil.isNotEmpty(droneInfos)) {
            // 如果类型为空,设为未知类型
            droneInfos.forEach(d->{
                if (StringUtils.isEmpty(d.getType())) {
                    d.setType("其它");
                }
            });
            Map<String, List<DroneInfo>> typeMap = droneInfos.stream().collect(Collectors.groupingBy(DroneInfo::getType));
            typeMap.forEach((k,v)-> result.put(dictMap.getOrDefault(k, k), v.size()));
        }
        return AjaxResult.success(result);
    }

    @ApiOperation("行动次数环比")
    @GetMapping("actionYearStatistics")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult actionYearStatistics()
    {
        JSONObject result = new JSONObject();
        result.put("month", Arrays.asList("一月,二月,三月,四月,五月,六月,七月,八月,九月,十月,十一月,十二月".split(",")));

        PlanAction planAction = new PlanAction();
        planAction.getParams().put("beginCreateTime", DateUtil.formatDateTime(DateUtil.beginOfYear(new Date())));
        planAction.getParams().put("endCreateTime", DateUtil.formatDateTime(DateUtil.endOfYear(new Date())));
        List<PlanAction> planActionsThisYear = planActionService.selectPlanActionList(planAction);
        planAction.getParams().put("beginCreateTime", DateUtil.formatDateTime(DateUtil.beginOfYear(DateUtil.offset(new Date(), DateField.YEAR, -1))));
        planAction.getParams().put("endCreateTime", DateUtil.formatDateTime(DateUtil.endOfYear(DateUtil.offset(new Date(), DateField.YEAR, -1))));
        List<PlanAction> planActionsLastYear = planActionService.selectPlanActionList(planAction);

        List<Integer> thisYearCount = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(planActionsThisYear)) {
            Map<Integer, List<PlanAction>> monthMap = planActionsThisYear.stream().collect(Collectors.groupingBy(p -> DateUtil.month(p.getCreateTime())));
            for (int i = 0; i < 12; i++) {
                thisYearCount.add(monthMap.getOrDefault(i, new ArrayList<>()).size());
            }
            result.put("this_year", thisYearCount);
        }


        List<Integer> lastYearCount = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(planActionsLastYear)) {
            Map<Integer, List<PlanAction>> monthMap = planActionsLastYear.stream().collect(Collectors.groupingBy(p -> DateUtil.month(p.getCreateTime())));
            for (int i = 0; i < 12; i++) {
                lastYearCount.add(monthMap.getOrDefault(i, new ArrayList<>()).size());
            }
            result.put("last_year", lastYearCount);
        }

        return AjaxResult.success(result);
    }

    @ApiOperation("查询N天的任务数量数据")
    @GetMapping("trDayCount")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult selectTrDayCount(@RequestBody IndexVo indexVo)
    {
//        JSONObject jb = new JSONObject();
        System.out.println(indexVo.getDay());
        List<Map<String , Object>> Dept= taskRecordService.selectTrDayCount(indexVo.getDay());
        return AjaxResult.success(Dept);
    }


    @ApiOperation("统计未来7天的巡航任务量(含当天)")
    @GetMapping("taskFutureStatistics")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult taskFutureStatistics()
    {
        List<JSONObject> result = new ArrayList<>();

        // 判断未来7天后是否跨月
        Date nowDay = new Date();
        Date after7Day = DateUtil.offsetDay(nowDay, 7);

        List<TaskVo> thisMonthTasks = taskCalendarService.getMonthTaskByMonthAndType(nowDay);
        List<TaskVo> allMonthTasks = new ArrayList<>(thisMonthTasks);
        if (!DateUtil.isSameMonth(nowDay, after7Day)) {
            List<TaskVo> nextMonthTasks = taskCalendarService.getMonthTaskByMonthAndType(after7Day);
            allMonthTasks.addAll(nextMonthTasks);
        }

        if (CollectionUtil.isEmpty(allMonthTasks)) {
            return AjaxResult.success(result);
        }

        List<JSONObject> dateTasks = taskCalendarService.processResultFormat(allMonthTasks);
        // 只取未来7天的任务数量
        for (int i = 0; i < 7; i++) {
            JSONObject dayStat = new JSONObject();
            Date day = DateUtil.offsetDay(new Date(), i);
            String dayStr = DateUtil.formatDate(day);
            int dayCount = (int) dateTasks.stream().filter(dt -> StringUtils.equals(dt.getString("date"), dayStr))
                    .mapToLong(e -> e.getList("task", TaskVo.class).size()).sum();
            dayStat.put("date", DateUtil.format(day, "MM-dd"));
            dayStat.put("count", dayCount);
            result.add(dayStat);
        }
        return AjaxResult.success(result);
    }

    @ApiOperation("进行中任务列表")
    @GetMapping("taskStatistics")
    @AesSecurityParameter(outEncode = true)
    public TableDataInfo taskStatistics(TaskRecord taskRecord)
    {
        startPage();
        List<TaskRecord> list = taskRecordService.selectTaskRecordList(taskRecord);
        return getDataTable(list);
    }

    @ApiOperation("航线使用机场比例")
    @GetMapping("routeDroneStatistics")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult routeDroneStatistics()
    {
        List<JSONObject> result = new ArrayList<>();
        List<RoutesInfo> routesInfos = routesInfoService.selectRoutesInfoList(new RoutesInfo());
        if (CollectionUtil.isEmpty(routesInfos)) {
            return AjaxResult.success(result);
        }
        routesInfos.forEach(r->{
            if (StringUtils.isEmpty(r.getAirportName())) {
                r.setAirportName("其它");
            }
        });
        Map<String, List<RoutesInfo>> airPortRouteMap = routesInfos.stream().collect(Collectors.groupingBy(RoutesInfo::getAirportName));
        airPortRouteMap.forEach((k,v)->{
            JSONObject item = new JSONObject();
            item.put("name", k);
            item.put("value", v.size());
            result.add(item);
        });
        return AjaxResult.success(result);
    }

    @ApiOperation("巡航记录月度总数环比")
    @GetMapping("taskTotalMonthly")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult taskTotalMonthly()
    {
        JSONObject result = new JSONObject();
        result.put("month", Arrays.asList("一月,二月,三月,四月,五月,六月,七月,八月,九月,十月,十一月,十二月".split(",")));

        TaskRecord taskRecord = new TaskRecord();
        taskRecord.getParams().put("beginTaskBeginTime", DateUtil.formatDateTime(DateUtil.beginOfYear(new Date())));
        taskRecord.getParams().put("endTaskBeginTime", DateUtil.formatDateTime(DateUtil.endOfYear(new Date())));
        List<TaskRecord> taskRecordThisYear = taskRecordService.selectTaskRecordList(taskRecord);
        taskRecord.getParams().put("beginTaskBeginTime", DateUtil.formatDateTime(DateUtil.beginOfYear(DateUtil.offset(new Date(), DateField.YEAR, -1))));
        taskRecord.getParams().put("endTaskBeginTime", DateUtil.formatDateTime(DateUtil.endOfYear(DateUtil.offset(new Date(), DateField.YEAR, -1))));
        List<TaskRecord> taskRecordLastYear = taskRecordService.selectTaskRecordList(taskRecord);

        List<Integer> thisYearCount = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(taskRecordThisYear)) {
            Map<Integer, List<TaskRecord>> monthMap = taskRecordThisYear.stream().collect(Collectors.groupingBy(p -> DateUtil.month(p.getTaskBeginTime())));
            for (int i = 0; i < 12; i++) {
                thisYearCount.add(monthMap.getOrDefault(i, new ArrayList<>()).size());
            }
            result.put("this_year", thisYearCount);
        }


        List<Integer> lastYearCount = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(taskRecordLastYear)) {
            Map<Integer, List<TaskRecord>> monthMap = taskRecordLastYear.stream().collect(Collectors.groupingBy(p -> DateUtil.month(p.getTaskBeginTime())));
            for (int i = 0; i < 12; i++) {
                lastYearCount.add(monthMap.getOrDefault(i, new ArrayList<>()).size());
            }
            result.put("last_year", lastYearCount);
        }

        return AjaxResult.success(result);


    }

}
